<?php
namespace app\common\service;

use think\Config;
use think\Log;
use think\Request;

class BaseService
{
    /**
     * 返回状态码
     *
     * @var string
     */
    protected $code = 1;

    /**
     * 日志记录类型.
     *
     * @var string
     */
    protected $logType = 'notice';

    /**
     * 返回状态信息.
     *
     * @var string
     */
    protected $msg = 'success';

    /**
     * 返回数据.
     *
     * @var array
     */
    protected $data = [];

    /**
     * 返回数据包(包含code和msg,data).
     *
     * @var array
     */
    protected $return = [];

    /**
     * 来源type 实例化service时传过来.
     *
     * @var int
     */
    protected $type;

    /**
     * redis连接对象.
     * @var object
     */
    protected $redis;

    public function __construct($type)
    {
        $this->return = [
            'code' => &$this->code,
            'msg' => &$this->msg,
            'data' => &$this->data,
        ];
        $this->type = $type;
        $this->_initialize();
    }

    /**
     * 记录错误与异常消息处理.
     *
     * @param $e
     * @param array $data
     * @param bool  $record
     */
    public function errorMessage($e, $data = [], $record = true)
    {
        if (($e instanceof \think\Exception)) {
            $this->msg = $e->getMessage();
            $this->code = $e->getCode();
            //防止系统错误信息直接暴露
            if ('40' !== mb_substr($e->getCode(), 0, 2)) {
                $errorData = Config::get('error.SYSTEM_ERROR');
                $this->msg = $errorData['msg'];
                $this->code = $errorData['code'];
                $this->logType = 'error';
            }
            if ($record) {
                $header = Request::instance()->header();
                // HTTP请求头信息的名称不区分大小写，并且 _ 会自动转换为 -
                $token = isset($header['x-token']) ? $header['x-token'] : '';
                $errorMsg = '请求头信息:X-Token:'.$token.PHP_EOL;
                $errorMsg .= $e->getMessage().' 在 '.$e->getFile().' '.$e->getLine().' 行'.PHP_EOL.$e->getTraceAsString();
                $errorMsg .= !empty($data) ? ' 相关参数：'.json_encode($data, JSON_UNESCAPED_UNICODE) : '';
                Log::record($errorMsg, $this->logType);
            }
        }
    }

    /**
     * 初始化操作.
     */
    protected function _initialize()
    {
    }
    
    /**
     * GET属性
     * 
     * @param string $name
     * @return unknown|NULL
     */
    public function __get($name)
    {
        if (property_exists($this, $name)){
            return $this->$name;
        }
        return null;
    }
}
